package com.zsr.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.service.BaiduTongJiApiService;
import com.zsr.example.util.HttpClient;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 百度统计api实现类
 * <br>文档地址:https://tongji.baidu.com/api/manual/Chapter2/openapi.html
 *
 * @author zhousiren
 * @date 2022/1/27 11:19
 */
@Service
public class BaiduTongJiApiServiceImpl implements BaiduTongJiApiService {
    //授权码
    private final String API_KEY = "NMHGDNRMSfTYxOg89x1ELyhGryKE9AuF";
    private final String SECRET_KEY = "uyVByEnAGtj48zF5Y3UdOwQZYht1eyVG";
    private final String SITE_ID = "17578189";
    //REFRESH_TOKEN的有效期为十年
    private  String refresh_token = "122.1b424045d7ba51811ebd2d35ee34b45d.YaQRJZ8gmIQfk6zDCVlCxfYK0m-w9fci9aPoKTT.5SmGTw";
    //ACCESS_TOKEN的有效期为一个月 ,通过REFRESH_TOKEN刷新ACCESS_TOKEN
    //todo 从redis中取 方便后台更改，或者刷新令牌
    private  String access_token = "121.b9bf72cffbef5c77c8e81b1b1f059dec.Y55R2CQcGq6cX7tZo7awIuGQQw7b6zCd65l8oJD.khB_Yg";
    //重置access_token步骤
    //1.访问链接 复制授权码 例如 1e551a8893d6d6b4feb128115d6230ea
    // http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=NMHGDNRMSfTYxOg89x1ELyhGryKE9AuF&redirect_uri=oob&scope=basic&display=popup
    //2.访问链接 code 为授权码，CLIENT_ID为 API_KEY，CLIENT_SECRET为SECRET_KEY
    //http://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code={CODE}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&redirect_uri=oob
    public void auth(String code){
        //code 由来 步骤1
        HttpClient httpClient=new HttpClient(" https://openapi.baidu.com/oauth/2.0/token");
        Map<String, String> param=new HashMap<>();
        param.put("grant_type","authorization_code");
        param.put("code",code);
        param.put("client_id",API_KEY);
        param.put("client_secret",SECRET_KEY);
        param.put("redirect_uri","oob");

        try {
            httpClient.get();
            String content = httpClient.getContent();
            JSONObject jsonObject = JSONObject.parseObject(content);
            this.refresh_token=jsonObject.getString("access_token");
            this.access_token=jsonObject.getString("refresh_token");

        } catch (Exception e) {
            throw new CommonJsonException("20001",e.getMessage());
        }
    }

    @Override
    public String refresh() {

        try {
            HttpClient client = new HttpClient(String.format("http://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s", refresh_token, API_KEY, SECRET_KEY));
            client.get();
            String content = client.getContent();
            JSONObject jsonObject = JSONObject.parseObject(content);
             if(!jsonObject.getString("error").isEmpty()){
                throw new CommonJsonException("20001", jsonObject.getString("error"));
            }
            return jsonObject.getString("access_token");


        } catch (Exception e) {
            throw new CommonJsonException("20001", e.getMessage());

        }

    }

    @Override
    public JSONObject getTimeTrendRpt() {
        //HttpClient httpClient=new HttpClient(String.format("https://openapi.baidu.com/rest/2.0/tongji/report/getData?access_token=%s&site_id=%s&method=overview/getTimeTrendRpt&start_date=20190101&end_date=20190105&metrics=pv_count,visitor_count,ip_count",ACCESS_TOKEN,SITE_ID));
        HttpClient httpClient2=new HttpClient("https://openapi.baidu.com/rest/2.0/tongji/report/getData");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Map<String, String> param=new HashMap<>();
        param.put("access_token",access_token);
        param.put("site_id",SITE_ID);
        param.put("method","overview/getTimeTrendRpt");
        param.put("start_date",simpleDateFormat.format(calendar.getTime()));
        param.put("end_date",simpleDateFormat.format(date));
        //浏览量，访客，ip数，跳出率，平均访问时长
        param.put("metrics","pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time");

        httpClient2.setParameter(param);
        try {
            httpClient2.setHttps(true);
            httpClient2.get();
            String content = httpClient2.getContent();
            JSONObject jsonObject = JSONObject.parseObject(content);
            String errorCode = jsonObject.getString("error_code");
            if(!StringUtils.isEmpty(errorCode)&& errorCode.equals("110")){
                //todo 刷新令牌
                throw new CommonJsonException("20001","访问令牌无效或不再有效");
            }
            //commonTrackRpt: {error_msg: "Access token expired", error_code: 111}
            else if(!StringUtils.isEmpty(errorCode)&& errorCode.equals("111")){
                throw new CommonJsonException("20001","访问令牌过期");
            }
            return jsonObject;

        }catch (CommonJsonException e){
            throw e;
        }catch (Exception e) {
            throw new CommonJsonException("20001","系统异常");
        }
    }

    /**
     *
     * @return
     */
    public JSONObject getCommonTrackRpt(){
        HttpClient httpClient=new HttpClient("https://openapi.baidu.com/rest/2.0/tongji/report/getData");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String format = simpleDateFormat.format(date);
        Map<String, String> param=new HashMap<>();
        param.put("access_token",access_token);
        param.put("site_id",SITE_ID);
        param.put("method","overview/getCommonTrackRpt");
        param.put("start_date",format.substring(0,format.length()-2)+"01");
        param.put("end_date",format);

        httpClient.setParameter(param);
        try {
            httpClient.setHttps(true);
            httpClient.get();
            String content = httpClient.getContent();
            JSONObject jsonObject = JSONObject.parseObject(content);
            String errorCode = jsonObject.getString("error_code");
            if(!StringUtils.isEmpty(errorCode)&& errorCode.equals("110")){
                //todo 刷新令牌
                throw new CommonJsonException("20001","访问令牌无效或不再有效");
            }

            return jsonObject;

        }catch (CommonJsonException e){
            throw e;
        }catch (Exception e) {
            throw new CommonJsonException("20001","系统异常");
        }
    }
}
